#!/bin/bash
########################################################################
# script name:  scp_exec.sh
# Used for:     SCp files to target host(s)
# Author:       Martin Dumont
# Contributors:
# Version:      0.1
#
# (date format: date +'%Y/%m/%d')
#
# Date          Version Contributors    Modifications
# ----------    ------- ------------    -------------
# 2011/11/09    0.1     MDUMONT         initial
########################################################################
usage()
{
cat << STOP

usage: $0 [options] [ARG]

This script is used for ....

OPTIONS:
   -h               Comma seperated list of hosts, or ALL
   -f               File to upload (to home directory)

Ex.:
$0 -h saprmt02 -f test.sh
$0 -h saprmt02,saprmt01 -f /tmp/test.sh
$0 -h ALL -f /tmp/test.sh

STOP
}
#######################################
# Get parameters
#######################################
while getopts h:f: OPTION
do
        case $OPTION in
        h)
                HOSTS=$(echo $OPTARG | tr [:upper:] [:lower:] | sed 's/,/ /g')
                ;;
        f)
                FILES=$(echo $OPTARG | sed 's/,/ /g')
                ;;
        \?)
                usage
                exit 1
                ;;
        *)
                usage
                exit 1
                ;;
        esac
done
if [ $OPTIND = 1 ]; then usage; exit 1; fi
if [ -z "$HOSTS" ]; then echo "Specify a host..."; usage; exit 1; fi
#######################################
# Functions
#######################################
BAENV=$(dirname `which $0`)/loadenv.sh
if [ -f $BAENV ]; then . $BAENV; else echo "No env library ($BAENV)"; exit 1; fi
SSH_OPTS=" -o ConnectTimeout=15 -o BatchMode=yes -o StrictHostKeyChecking=no -o LogLevel=quiet"
#######################################
# MAIN
#######################################
for i in $FILES
do
   if [[ -f "$i" ]]; then NEWFILES="$NEWFILES $i"; fi
done
NEWFILES=$(echo $NEWFILES | sed 's/^ //g')
FILES=$NEWFILES
echo "Files: $FILES"
HOSTLIST=$(checkhost $HOSTS | egrep -v 'Verifying')
for HOSTNAME in $HOSTLIST
do
	for i in $FILES
	do
		echo -e "Scping file $i to $HOSTNAME ... \c"
		scp -B -q $i $HOSTNAME:$i && echo -e ok || echo -e failed
	done
done
#######################################
exit 0
